package com.sos.service.impl;

import com.sos.exception.CustomException;
import com.sos.exception.ErrorCode;
import com.sos.model.dto.HelperInfoDTO;
import com.sos.model.dto.HelperInfoUpdateDTO;
import com.sos.model.entity.HelperInfo;
import com.sos.model.entity.User;
import com.sos.model.vo.ResultVO;
import com.sos.repository.HelperInfoRepository;
import com.sos.repository.UserRepository;
import com.sos.service.HelperInfoService;
import com.sos.util.UserContextUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class HelperInfoServiceImpl implements HelperInfoService {

    private final HelperInfoRepository helperInfoRepository;
    private final UserRepository userRepository;
    private final UserContextUtils userContextUtils;

    @Override
    @Transactional
    public ResultVO<HelperInfo> addHelperInfo(HelperInfoDTO helperInfoDTO) {
        // 1. 获取当前用户
        Long userId = userContextUtils.getCurrentUserId();
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new CustomException(ErrorCode.USER_NOT_FOUND));

        // 2. 检查是否已经存在帮助者信息
        if (helperInfoRepository.findByUserId(userId) != null) {
            throw new CustomException(ErrorCode.HELPER_INFO_ALREADY_EXISTS);
        }

        // 3. 创建帮助者信息
        HelperInfo helperInfo = new HelperInfo();
        BeanUtils.copyProperties(helperInfoDTO, helperInfo);
        helperInfo.setUserId(userId);

        // 4. 保存到数据库
        HelperInfo savedHelperInfo = helperInfoRepository.save(helperInfo);

        return ResultVO.success(savedHelperInfo);
    }

    @Override
    @Transactional
    public ResultVO<HelperInfo> updateHelperInfo(Long helperInfoId, HelperInfoUpdateDTO updateDTO) {
        // 1. 获取当前用户
        Long userId = userContextUtils.getCurrentUserId();

        // 2. 查找帮助者信息
        HelperInfo helperInfo = helperInfoRepository.findById(helperInfoId)
                .orElseThrow(() -> new CustomException(ErrorCode.HELPER_INFO_NOT_FOUND));

        // 3. 验证权限（只能修改自己的信息）
        if (!helperInfo.getUserId().equals(userId)) {
            throw new CustomException(ErrorCode.UNAUTHORIZED_OPERATION);
        }

        // 4. 更新字段
        if (updateDTO.getSkills() != null) helperInfo.setSkills(updateDTO.getSkills());
        if (updateDTO.getServiceRadius() != null) helperInfo.setServiceRadius(updateDTO.getServiceRadius());
        if (updateDTO.getOnlineStatus() != null) helperInfo.setOnlineStatus(updateDTO.getOnlineStatus());
        if (updateDTO.getLastLatitude() != null) helperInfo.setLastLatitude(updateDTO.getLastLatitude());
        if (updateDTO.getLastLongitude() != null) helperInfo.setLastLongitude(updateDTO.getLastLongitude());
        if (updateDTO.getRating() != null) helperInfo.setRating(updateDTO.getRating());

        // 5. 保存更新
        HelperInfo updatedHelperInfo = helperInfoRepository.save(helperInfo);

        return ResultVO.success(updatedHelperInfo);
    }

    @Override
    @Transactional
    public ResultVO<HelperInfo> updateCurrentHelperInfo(HelperInfoUpdateDTO updateDTO) {
        // 1. 获取当前用户
        Long userId = userContextUtils.getCurrentUserId();

        // 2. 查找帮助者信息
        HelperInfo helperInfo = helperInfoRepository.findByUserId(userId);
        if (helperInfo == null) {
            throw new CustomException(ErrorCode.HELPER_INFO_NOT_FOUND);
        }

        // 3. 更新字段
        if (updateDTO.getSkills() != null) helperInfo.setSkills(updateDTO.getSkills());
        if (updateDTO.getServiceRadius() != null) helperInfo.setServiceRadius(updateDTO.getServiceRadius());
        if (updateDTO.getOnlineStatus() != null) helperInfo.setOnlineStatus(updateDTO.getOnlineStatus());
        if (updateDTO.getLastLatitude() != null) helperInfo.setLastLatitude(updateDTO.getLastLatitude());
        if (updateDTO.getLastLongitude() != null) helperInfo.setLastLongitude(updateDTO.getLastLongitude());
        if (updateDTO.getRating() != null) helperInfo.setRating(updateDTO.getRating());

        // 4. 保存更新
        HelperInfo updatedHelperInfo = helperInfoRepository.save(helperInfo);

        return ResultVO.success(updatedHelperInfo);
    }

    @Override
    public ResultVO<HelperInfo> getHelperInfo() {
        // 1. 获取当前用户
        Long userId = userContextUtils.getCurrentUserId();

        // 2. 查找帮助者信息
        HelperInfo helperInfo = helperInfoRepository.findByUserId(userId);
        if (helperInfo == null) {
            throw new CustomException(ErrorCode.HELPER_INFO_NOT_FOUND);
        }

        return ResultVO.success(helperInfo);
    }

    @Override
    public ResultVO<HelperInfo> getHelperInfoById(Long id) {
        // 1. 查找帮助者信息
        HelperInfo helperInfo = helperInfoRepository.findById(id)
                .orElseThrow(() -> new CustomException(ErrorCode.HELPER_INFO_NOT_FOUND));

        return ResultVO.success(helperInfo);
    }
}